<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板类型"
                    prop="templatetype"
      >
        <el-select v-model="queryParams.templatetype"
                   placeholder="请选择"
                   class="filter-item"
                   style="width: 220px"
                   @change="handleQuery"
        >
          <el-option
            v-for="dict in operation_template_list"
            :key="dict.label"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['operation:operationdaily:add']"
        >新增</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="Plus"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['operation:operationdaily:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->
    <el-table
              v-loading="loading"
              :data="operationdailyList"
              highlight-current-row
              :span-method="arraySpanMethod(operationdailyList)"
              @selection-change="handleSelectionChange"
              width="100%"
    >
      <el-table-column :label="title" align="center">
        <template #header>
          <dict-tag :options="operation_template_list" :value="queryParams.templatetype"/>
        </template>
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" width="50"/>
        <el-table-column label="清算流程分段" align="center">
          <el-table-column label="工作内容" prop="summary" width="300"/>
          <el-table-column label="时间" prop="operatetime" width="120"/>
        </el-table-column>
        <el-table-column label="清算工作具体内容" align="left" prop="content">
          <template #default="scope">
<!--            <pre>{{scope.row.content}}</pre>-->
            <span v-html="scope.row.content" style="white-space:pre-wrap"/>
          </template>
        </el-table-column>
        <el-table-column label="是否启用" align="center" prop="flag" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.flag==1" type="success">是</el-tag>
            <el-tag v-else type="danger">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="周期" align="center" prop="period" width="80"/>
        <el-table-column label="特定日期" align="center" prop="specificdate" width="120">
          <template #default="scope">
            <span>{{parseTime(scope.row.specificdate,'{y}-{m}-{d}')}}</span>
          </template>
        </el-table-column>
        <el-table-column label="关联系统" align="left" prop="busisystems">
          <template #default="scope">
            <el-tag v-for="id in scope.row.busisystems!=undefined&&scope.row.busisystems!=''?scope.row.busisystems.split(','):''">
              {{systemList.filter(item=>item.id===id)[0]===undefined?'':systemList.filter(item=>item.id===id)[0].name}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" width="80"/>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)" icon="link">修改</el-button>
<!--            <el-button link type="primary" @click="handleDelete(scope.row)" icon="close">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="title"
      v-model="open"
      width="700px" append-to-body>
      <el-form ref="operationdailyRef" label-position="right" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="模板类型"
                      prop="templatetype"
        >
          <el-select v-model="queryParams.templatetype"
                     disabled
                     placeholder="请选择"
                     class="filter-item"
                     style="width: 220px"
                     @change="handleQuery"
          >
            <el-option
              v-for="dict in operation_template_list"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间"
                      prop="operatetime">
            <el-input
              v-model="form.operatetime"
              placeholder="请输入时间"
            />
        </el-form-item>
        <el-form-item label="工作内容"
                      prop="summary">
            <el-input
              v-model="form.summary"
              placeholder="请输入工作内容"
            ></el-input>
        </el-form-item>
        <el-form-item label="清算工作具体内容"
                      prop="content"
        >
          <editor v-model="form.content" :min-height="196"/>
        </el-form-item>
        <el-form-item label="是否启用" prop="flag">
          <el-select
            v-model="form.flag"
          >
            <el-option label="否" value="0"/>
            <el-option label="是" value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="周期" prop="prefix">
          <el-input
            v-model="form.day"
            type="number"
            placeholder="填写具体的数字，当选择D/T时，可不填"
          >
            <template #prepend>
              <el-select v-model="form.prefix" style="width: 120px" placeholder="选择第几天">
                <el-option label="D" value="D"></el-option>
                <el-option label="T" value="T"></el-option>
                <el-option label="W" value="W"></el-option>
                <el-option label="M" value="M"></el-option>
                <el-option label="Q" value="Q"></el-option>
              </el-select>
            </template>
          </el-input>
          <span @click="showExample" style="cursor: pointer"><strong>D：表示自然日，T：表示工作日，W：表示周，M：表示月，Q：表示季</strong></span>
          <span v-if="example">
            <strong>example：W1:表示每周第一个工作日 W-1表示每周倒数第一个工作日</strong><br>
            <strong>example：M1:表示每月第一个工作日 W-1表示每月倒数第一个工作日</strong><br>
            <strong>example：Q1:表示每月第一个工作日 Q-1表示每月倒数第一个工作日</strong><br>
          </span>

        </el-form-item>
        <el-form-item label="特定日期" prop="specificdate">
          <el-date-picker
            v-model="form.specificdate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择特定日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="关联系统"
                      prop="busisystemList">
          <el-select
            v-model="form.busisystemList"
            placeholder="请选择关联系统"
            multiple
          >
            <el-option
              v-for="item in systemList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :step="0.1" placeholder="排序"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" icon="check" @click="submitForm">确 定</el-button>
          <el-button @click="cancel" icon="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Operationdaily">
import { listOperationdaily, getOperationdaily, delOperationdaily, addOperationdaily, updateOperationdaily } from "@/api/operation/operationdaily";
import {parseTime} from "@/utils/ruoyi";
import {getSysList} from "@/api/operation/sqltool";
import {computed, getCurrentInstance} from "vue";
import DictTag from "@/components/DictTag/index.vue";
const { proxy } = getCurrentInstance();
const {operation_template_list}= proxy.useDict("operation_template_list");
const operationdailyList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const systemList = ref([]);
const example = ref(false);
const pickDate = parseTime(new Date(),"{y}-{m}-{d}");
// 自定义两位小数校验规则
const validateTwoDecimal = (rule, value, callback) => {
  console.log(value)
  if (value === '') {
    callback(new Error('请输入内容'));
  } else {
    // 正则表达式：可选负号，数字，可选小数点后最多两位数字
    const reg = /^-?\d+(\.\d{1,2})?$/;
    if (!reg.test(value)) {
      callback(new Error('请输入有效的数字，最多两位小数'));
    } else {
      callback();
    }
  }
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templatetype: '1',
    summary: undefined,
    operatetime: undefined,
    content: undefined,
    period: undefined,
    specificdate: undefined,
    sort: undefined,
    flag: undefined,
    busioperations: undefined,
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    templatetype: [
      { required: true, message: "模板不能为空", trigger: "change" }
    ],
    summary: [
      { required: true, message: "工作内容不能为空", trigger: "blur" }
    ],
    operatetime: [
      { required: true, message: "模板时间不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "工作具体内容不能为空", trigger: "blur" }
    ],
    prefix: [
      { required: true, message: "周期标识不可为空", trigger: "blur" },
    ],
    specificdate: [
      { required: false, message: "用于生成单独一日的任务，如果特定日期要可选，周期必须选M不能为空", trigger: "blur" }
    ],
    sort: [
      { required: true, message: "排序不能为空", trigger: "blur"},
      { validator: validateTwoDecimal, trigger: 'blur' }
    ],
    flag: [
      { required: true, message: "0：不启用；1:启用；不能为空", trigger: "blur" }
    ],
    busioperations: [
      { required: false, message: "涉及业务系统id，用逗号分割不能为空", trigger: "blur" }
    ],
  }
});
const handleBusiData = (value)=>{
  console.log(value)
  return value.split(",")
}


const { queryParams, form, rules } = toRefs(data);
const title = ref("")
/** 查询运营部门日志记录列表 */
function getList() {
  loading.value = true;
  listOperationdaily(queryParams.value).then(response => {
    operationdailyList.value = response;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    templatetype: null,
    summary: null,
    operatetime: null,
    // content: null,
    period: null,
    specificdate: null,
    sort: null,
    flag: null,
    busioperations: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("operationdailyRef");
}

/** 搜索按钮操作 */
function handleQuery(value) {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}


function getBusiList(){
  getSysList().then(response => {
    systemList.value = response.rows;
    console.log(systemList,"====");
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  if(queryParams.value.templatetype==='1'){
    title.value = "资金业务检查清单";
  }else{
    title.value='TA日志表'
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getOperationdaily(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    form.value.prefix = response.data.period.slice(0,1);
    form.value.day = response.data.period.split(form.value.prefix)[1]
    if(response.data.busisystems!=undefined&&response.data.busisystems.length!=0){
      form.value.busisystemList = response.data.busisystems.split(",");
    }
    open.value = true;
    title.value = "修改模板";
  });
}

/** 提交按钮 */
function submitForm() {
  form.value.templatetype = queryParams.value.templatetype;
  let day = form.value.day===undefined?'':form.value.day;
  form.value.period = form.value.prefix+day
  console.log(form.value.period,"=====")
  proxy.$refs["operationdailyRef"].validate(valid => {
    if (valid) {
      form.value.templatetype = queryParams.value.templatetype;
      buttonLoading.value = true;
      if (form.value.id != null) {
        if(form.value.busisystemList!=undefined&&form.value.busisystemList.length!=0){
          form.value.busisystems = form.value.busisystemList.join(",");
        }else{
          form.value.busisystems = ''
        }
        updateOperationdaily(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        console.log(form.value.busisystemList,"=====")
        if(form.value.busisystemList!=undefined&&form.value.busisystemList.length!=0){
          form.value.busisystems = form.value.busisystemList.join(",");
        }
        addOperationdaily(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}
function arraySpanMethod(tableData){
  console.log("========",tableData)
  const mergingRows = (tableData) => {
    // 表格数据列合并预处理,生成一个与行数相同的数组记录每一行设置的合并数
    // 如果是第一条记录（索引为0），向数组中加入1，并设置索引位置；
    // 如果不是第一条记录，则判断它与前一条记录是否相等，如果相等，
    // 则向mergingRows中添入元素0，并将前一位元素+1，表示合并行数+1，
    // 以此往复，得到所有行的合并数，0即表示该行不显示。
    const mergingRows = []
    let mergingPos = 0
    for (let i = 0; i < tableData.length; i++) { // tabledata 表格数据源
      if (i === 0) {
        mergingRows.push(1)
        mergingPos = 0
      } else {
        if (tableData[i].operatetime === tableData[i - 1].operatetime&&tableData[i].summary === tableData[i - 1].summary) {
          // 哪些数据是要合并的 合并的条件是什么 此处合并条件为categoryName 相同则进行合并
          mergingRows[mergingPos] += 1
          mergingRows.push(0)
        } else {
          mergingRows.push(1)
          mergingPos = i
        }
      }
    }
    return mergingRows
  }
  const data = mergingRows(tableData)
  console.log(data,"变更之后的数据=======")
  return ({rowIndex, columnIndex }) => {
    if (columnIndex === 2||columnIndex===3) { // 第一列
      const _row = data[rowIndex]
      const _col = _row > 0 ? 1 : 0
      return {
        rowspan: _row,
        colspan: _col
      }
    }
  }
}

function showExample(){
  example.value = !example.value
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除工作内容为"' +row.summary + '"的模板项？').then(function() {
    loading.value = true;
    return delOperationdaily(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('operation/operationdaily/export', {
    ...queryParams.value
  }, `operationdaily_${new Date().getTime()}.xlsx`)
}
getBusiList();
getList();
</script>
